<template>
	<view class="blood-sugar-container" :class="{ 'modal-open': showBindModal }">
		<!-- 最新血糖 -->
		<view class="latest-blood-sugar" v-if="!showBindModal">
			<view class="section-header">
				<text>最新血糖</text>
				<view class="view-more" style="z-index: 99;" @click="toMoreBloodSugar">查看更多 ></view>
			</view>
			<view class="charts-box">
				<qiun-data-charts type="arcbar" :opts="opts" :chartData="chartData" canvas-id="bloodSugarArc" />
			</view>
			<view class="measure-time" v-if="records.length>0">测量日期：{{records[0].measuredTime}} <span
					style="padding-left: 10px;" :style="{color: records[0].color}">{{ records[0].tag}}</span></view>
		</view>

		<!-- 血糖趋势 -->
		<view class="blood-sugar-trend">
			<view class="section-header">
				<text>血糖趋势</text>
				<text class="view-more">查看详情 ></text>
			</view>
			<view class="date-filter">
				<view class="filter-buttons">
					<text :class="{ active: activeFilter === 'week7' }" @click="switchFilter('week7')">近七天</text>
					<text :class="{ active: activeFilter === 'day' }" @click="switchFilter('day')">日</text>
					<text :class="{ active: activeFilter === 'week' }" @click="switchFilter('week')">周</text>
					<text :class="{ active: activeFilter === 'month' }" @click="switchFilter('month')">月</text>
				</view>
				<view class="date-picker-range">
					<picker mode="date" :value="startDate" @change="onStartDateChange">
						<text>{{startDate}}</text>
					</picker>
					<text class="separator">至</text>
					<picker mode="date" :value="endDate" @change="onEndDateChange">
						<text>{{endDate}}</text>
					</picker>
				</view>
			</view>
			<view class="chart-container" v-if="!showBindModal">
				<qiun-data-charts type="line" :opts="trendOpts" :chartData="trendChartData" />
			</view>
			<view class="legend">
				<view class="legend-item">
					<view class="legend-label">
						<view class="dot normal"></view>
						<text>正常</text>
					</view>
					<text class="count">{{statistics.normalCount}}次</text>
				</view>
				<view class="legend-item">
					<view class="legend-label">
						<view class="dot high"></view>
						<text>高血糖</text>
					</view>
					<text class="count high">{{statistics.highCount}}次</text>
				</view>
				<view class="legend-item">
					<view class="legend-label">
						<view class="dot low"></view>
						<text>低血糖</text>
					</view>
					<text class="count low">{{statistics.lowCount}}次</text>
				</view>
			</view>
		</view>

		<!-- 血糖对比 -->
		<!-- <view class="blood-sugar-compare">
			<view class="section-header">
				<text>血糖对比</text>
			</view>
			<view class="date-filter">
				<text :class="{ active: activeCompareFilter === 'day' }" @click="switchCompareFilter('day')">按天</text>
				<text :class="{ active: activeCompareFilter === 'week' }" @click="switchCompareFilter('week')">按周</text>
				<text :class="{ active: activeCompareFilter === 'month' }"
					@click="switchCompareFilter('month')">按月</text>
			</view>
				<view class="date-selector">
				<view class="date-item">
					<text>选择日期:</text>
					<text class="date">2025-03-02 ></text>
				</view>
				<view class="date-item">
					<text>对比日期:</text>
					<text class="date">2025-03-01 ></text>
				</view>
			</view>
			<view class="chart-container">
				<qiun-data-charts type="line" :opts="compareOpts" :chartData="compareChartData" />
			</view>
		</view> -->

		<!-- 数据记录 -->
		<view class="data-records">
			<view class="section-header">
				<text>数据记录</text>
				<text class="view-more" @click="toMoreBloodSugar">查看更多</text>
			</view>
			<!-- 分页滚动容器 -->
			<scroller @init="initScroller" @down="refreshData" @up="loadMoreRecords" :up="optUp" :fixed="false">
				<view class="record-item" v-for="(item, index) in allRecords" :key="index" v-if="allRecords.length>0">
					<view class="record-main">
						<text class="value">血糖：{{item.bloodGlucose}}mmol/L</text>
						<text>状态：<text :style="{color: item.color}">{{ item.tag}}</text></text>
					</view>
					<view class="record-sub">
						<text>类型：{{ item.measuredType | dictFindType(dictsList) }}</text>
						<text>上传方式：{{ item.sourceName }}</text>
					</view>
					<view class="record-time">测量时间：{{item.measuredTime}}</view>
				</view>
				<!-- 空状态 -->
				<view class="empty-state" v-if="allRecords.length === 0 && !isLoading">
					<text>暂无数据记录</text>
				</view>
			</scroller>
		</view>

		<!-- 血糖参考值 -->
		<view class="reference-values">
			<view class="section-header">
				<text>血糖参考</text>
				<text class="unit">单位：mmol/L</text>
			</view>
			<view class="reference-table">
				<view class="table-row header">
					<view class="cell">测量时间</view>
					<view class="cell">空腹</view>
					<view class="cell">餐后1小时</view>
					<view class="cell">餐后2小时</view>
					<view class="cell">餐后3小时</view>
				</view>
				<view class="table-row" v-for="(row, index) in referenceData" :key="index">
					<view class="cell">{{row.name}}</view>
					<view class="cell">{{row.values[0]}}</view>
					<view class="cell">{{row.values[1]}}</view>
					<view class="cell">{{row.values[2]}}</view>
					<view class="cell">{{row.values[3]}}</view>
				</view>
			</view>
			<view class="description">
				<text>注：</text>
				<text>1.空腹指早晨6~8点，且8小时未进食除水以外的其他食物</text>
				<text>2.餐后时间一般指从进食第一口开始计时（即你开始吃饭时）</text>
				<text>3.以上数据仅供参考，不作为治疗及诊断依据；</text>
			</view>
			<view class="reference-table-footer">

			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="bottom-button">
			<text class="bind-device" @click="showBindDeviceModal">绑定设备</text>
			<button class="add-record" @click="addRecord">添加血糖</button>
		</view>
		
		<!-- 绑定设备弹窗 -->
		<view v-if="showBindModal" class="bind-modal-overlay" @click="hideBindDeviceModal">
			<view class="bind-modal" @click.stop>
				<view class="modal-header">
					<text class="modal-title">绑定设备</text>
					<text class="modal-close" @click="hideBindDeviceModal">×</text>
				</view>
				
				<view class="modal-content">
					<view class="input-group">
						<text class="input-label">请输入设备SN码</text>
						<input 
							class="sn-input" 
							v-model="deviceSnCode" 
							placeholder="请输入设备SN码"
							maxlength="50"
							@input="onSnCodeInput"
						/>
					</view>
					
					<view class="modal-tips">
						<text class="tips-text">• SN码通常位于设备底部或包装盒上</text>
						<text class="tips-text">• 请确保输入正确的SN码</text>
					</view>
				</view>
				
				<view class="modal-footer">
					<button class="modal-btn cancel-btn" @click="hideBindDeviceModal">取消</button>
					<button class="modal-btn confirm-btn" @click="confirmBindDevice" :disabled="!deviceSnCode.trim()">确认</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import scroller from '@/components/scroller/scroller.vue';
	import {
		addGlucose,
		listGlucose,
		queryTrendList,
		statisticsExce,
		queryTypeList,
		bindSn
	} from '@/api/healthData/everyGlucose.js'

	export default {
		data() {
			return {
				userId: this.$store.state.user.userId,
				records: [],
				allRecords: [], // 所有记录数据，用于分页显示
				dictsList: [],
				targetId: '',
				
				// 分页相关
				scroller: {},
				optUp: {
					onScroll: true,
					page: {
						size: 2// 每页加载10条记录
					}
				},
				isLoading: false,
				
				// 绑定设备相关状态
				showBindModal: false,
				deviceSnCode: '',
				startDate: (() => {
					const date = new Date();
					date.setDate(date.getDate() - 6);
					return this.formatDate(date);
				})(),
				endDate: this.formatDate(new Date()),
				statistics: {
					normalCount: 0,
					highCount: 0,
					lowCount: 0
				},
				opts: {
					type: 'arcbar',
					canvasId: 'bloodSugarArc',
					width: 180,
					height: 180,
					background: '#FFFFFF',
					animation: true,
					dataLabel: false,
					title: {
						name: "",
						color: '#333333',
						fontSize: 36,
						offsetY: -30
					},
					subtitle: {
						name: "mmol/L",
						color: '#999999',
						fontSize: 14,
						offsetY: -10
					},
					extra: {
						arcbar: {
							type: 'default',
							width: 12,
							backgroundColor: '#F5F5F5',
							startAngle: 0.8,
							endAngle: 0.2,
							gap: 2,
							linearType: 'none',
							roundCap: true
						}
					}
				},
				chartData: {
					series: [{
						name: "血糖值",
						color: '#fb3f3f',
						data: 0.0
					}]
				},
				trendOpts: {
					color: ['#4cd8aa', '#ff4d4f', '#1890ff'],
					padding: [15, 15, 0, 15],
					enableScroll: true, // 启用水平滚动
					legend: false,
					width: 350, // 设置图表宽度，确保滚动功能正常
					xAxis: {
						disableGrid: true,
						fontSize: 12,
						color: '#666666',
						scrollShow: true, // 启用横坐标滚动
						itemCount: 7, // 默认显示7个标签
						scrollAlign: 'left', // 滚动对齐方式
						scrollBackgroundColor: '#f8f8f8', // 滚动背景色
						scrollColor: '#1890ff', // 滚动条颜色
						scrollAnimation: true, // 启用滚动动画
						scrollAnimationDuration: 300 // 滚动动画时长
					},
					yAxis: {
						gridType: 'dash',
						dashLength: 4,
						data: [{
							min: 0,
							max: 20,
							format: 'val'
						}]
					},
					extra: {
						line: {
							type: 'straight',
							width: 2
						},
						area: {
							opacity: 0.2,
							gradient: true
						},
						point: {
							size: 3,
							borderWidth: 2,
							strokeColor: '#FFFFFF'
						},
						tooltip: {
							showBox: true,
							showArrow: true,
							borderWidth: 0,
							borderRadius: 4,
							fontColor: '#000',
							formatter: (item, category, index) => {
								// 设置tooltip背景色
								return {
									text: `血糖值: ${item.data}mmol/L`,
									color: '#4cd8aa',
									bgColor: '#4cd8aa'
								}
							}
						}
					}
				},
				trendChartData: {
					categories: [],
					series: [{
						name: '血糖值',
						data: [0]
					}]
				},
				compareOpts: {
					color: ['#2fc25b', '#ff9f40'],
					padding: [15, 15, 0, 15],
					enableScroll: false,
					legend: {
						show: true,
						position: 'bottom',
						float: 'center',
						padding: 10,
						margin: 0
					},
					xAxis: {
						disableGrid: true,
						fontSize: 12,
						color: '#666666'
					},
					yAxis: {
						gridType: 'dash',
						dashLength: 4,
						data: [{
							min: 0,
							max: 20,
							format: 'val'
						}]
					},
					extra: {
						line: {
							type: 'straight',
							width: 2
						}
					}
				},
				compareChartData: {
					categories: ['12:00', '14:00', '16:00', '17:00', '18:00', '20:00', '22:00'],
					series: [{
							name: '2025-03-02',
							data: [5.5, 8.0, 7.5, 6.8, 7.2, 6.5, 5.8]
						},
						{
							name: '2025-03-01',
							data: [6.0, 8.5, 7.8, 7.0, 7.5, 6.8, 6.0]
						}
					]
				},
				records: [],
				referenceData: [{
						name: '正常',
						values: ['4.4-6.1', '6.7-8.3', '5.0-7.2', '4.4-6.7']
					},
					{
						name: '尚可',
						values: ['6.1-7.2', '8.3-9.9', '7.2-8.8', '6.7-8.2']
					},
					{
						name: '一般',
						values: ['7.2-8.2', '10.0-12.7', '8.9-11.0', '8.3-9.9']
					},
					{
						name: '不良',
						values: ['8.3-9.9', '12.7-16.1', '11.1-15.3', '10.0-14.4']
					},
					{
						name: '非常不良',
						values: ['>10.0', '>16.6', '>15.5', '>14.4']
					}
				],
				activeFilter: 'week7',
				activeCompareFilter: 'day'
			};
		},
		created() {
			// this.$dict.getDicts('glucose_type').then(res => {
			// 	this.dictsList = res.data
			// })
			
		},
		onShow() {
			this.loadData() // 使用新的分页加载方法
			this.queryTrendList()
		},
		onLoad(options) {
			this.targetId = options.targetId
			this.queryTypeList()
		},
		methods: {
			// 分页相关方法
			initScroller(scroller) {
				this.scroller = scroller;
			},
			
			refreshData() {
				this.loadData();
			},
			
			loadData() {
				this.allRecords = [];
				this.scroller.resetUpScroll();
			},
			
			async loadMoreRecords() {
				this.isLoading = true;
				try {
					const queryParams = {
						userId: this.userId,
						pageNum: this.scroller.num,
						pageSize: this.scroller.size
					};
					
					const res = await listGlucose(queryParams);
					console.log('分页数据:', res);
					
					if (res.rows && res.rows.length > 0) {
						// 合并新数据
						this.allRecords = this.allRecords.concat(res.rows);
						
						// 如果是第一页，更新records用于图表显示
						if (this.scroller.num === 1) {
							this.records = res.rows.slice(0, 2);
							this.updateChartData(res.rows);
						}
					}
					
					this.scroller.endBySize(res.rows ? res.rows.length : 0, res.total || 0);
					this.$forceUpdate();
				} catch (error) {
					console.error('加载数据失败:', error);
					uni.showToast({
						title: '加载失败，请重试',
						icon: 'none'
					});
				} finally {
					this.isLoading = false;
					uni.stopPullDownRefresh();
					uni.hideLoading();
				}
			},
			
			updateChartData(rows) {
				if (rows.length > 0) {
					// 计算血糖值在0-15范围内的比例
					const bloodGlucose = parseFloat(rows[0].bloodGlucose) || 0;
					const proportion = bloodGlucose / 15;
					
					// 更新图表数据
					this.chartData = {
						series: [{
							name: "血糖值",
							color: rows[0].color || '#fb3f3f',
							data: proportion
						}]
					};
					
					// 更新opts配置
					this.opts = {
						...this.opts,
						title: {
							...this.opts.title,
							name: rows[0].bloodGlucose || '0.0',
							color: rows[0].color || '#fb3f3f'
						}
					};
				}
			},
			
			// 绑定设备相关方法
			showBindDeviceModal() {
				this.showBindModal = true
				this.deviceSnCode = ''
			},
			
			hideBindDeviceModal() {
				this.showBindModal = false
				this.deviceSnCode = ''
			},
			
			onSnCodeInput(event) {
				this.deviceSnCode = event.detail.value
			},
			
			confirmBindDevice() {
				if (!this.deviceSnCode.trim()) {
					uni.showToast({
						title: '请输入设备SN码',
						icon: 'none'
					})
					return
				}
				
				// 验证SN码格式（可以根据实际需求调整）
				if (this.deviceSnCode.trim().length < 6) {
					uni.showToast({
						title: 'SN码格式不正确',
						icon: 'none'
					})
					return
				}
				
				// 显示加载状态
				uni.showLoading({
					title: '绑定中...'
				})
				
				// 这里调用绑定设备的API
				this.bindDevice(this.deviceSnCode.trim())
			},
			
			bindDevice(snCode) {
				console.log('绑定设备SN码:', snCode)
				
				// 显示加载状态
				uni.showLoading({
					title: '绑定中...'
				})
				
				bindSn({sn: snCode}).then(res => {
					uni.hideLoading()
					
					if(res.code === 200){
						uni.showToast({
							title: '设备绑定成功',
							icon: 'success'
						})
						this.hideBindDeviceModal()
					} else {
						uni.showToast({
							title: res.message || '绑定失败',
							icon: 'none'
						})
					}
				}).catch(error => {
					uni.hideLoading()
					console.error('绑定设备失败:', error)
					uni.showToast({
						title: '网络错误，请重试',
						icon: 'none'
					})
				})
			},
			
			switchFilter(type) {
				this.activeFilter = type;

				// 设置默认日期范围
				const today = new Date();
				switch (type) {
					case 'week7':
						// 计算7天前的日期
						const sevenDaysAgo = new Date(today);
						sevenDaysAgo.setDate(today.getDate() - 6);
						this.startDate = this.formatDate(sevenDaysAgo);
						this.endDate = this.formatDate(today);
						break;
					case 'day':
						this.startDate = this.formatDate(today);
						this.endDate = this.formatDate(today);
						break;
					case 'week':
						// 计算本周的周一
						const weekMonday = new Date(today);
						weekMonday.setDate(today.getDate() - today.getDay() + (today.getDay() === 0 ? -6 : 1));
						// 计算本周的周日
						const weekSunday = new Date(weekMonday);
						weekSunday.setDate(weekMonday.getDate() + 6);

						this.startDate = this.formatDate(weekMonday);
						this.endDate = this.formatDate(weekSunday);
						break;
					case 'month':
						const monthStart = new Date(today.getFullYear(), today.getMonth(), 1);
						this.startDate = this.formatDate(monthStart);
						this.endDate = this.formatDate(today);
						break;
				}

				this.queryTrendList()
				// 根据不同类型更新图表数据
				switch (type) {
					case 'week7':
						// 生成近7天的日期标签
						const dateLabels = [];
						const tempDate = new Date(today);
						for (let i = 6; i >= 0; i--) {
							tempDate.setDate(today.getDate() - i);
							const month = String(tempDate.getMonth() + 1).padStart(2, '0');
							const day = String(tempDate.getDate()).padStart(2, '0');
							dateLabels.push(`${month}-${day}`);
						}
						// 7天数据，显示所有标签，但保持滚动配置
						this.trendOpts = {
							...this.trendOpts,
							enableScroll: true, // 保持滚动启用
							xAxis: {
								...this.trendOpts.xAxis,
								scrollShow: true, // 保持滚动启用
								itemCount: 7
							}
						};
						this.trendChartData = {
							categories: dateLabels,
							series: [{
								name: '血糖值',
								data: [5.5, 6.2, 8.5, 7.8, 6.5, 5.8, 6.0]
							}]
						};
						break;
					case 'day':
						// 日数据，7个时间点，显示所有标签，但保持滚动配置
						this.trendOpts = {
							...this.trendOpts,
							enableScroll: true, // 保持滚动启用
							xAxis: {
								...this.trendOpts.xAxis,
								scrollShow: true, // 保持滚动启用
								itemCount: 7
							}
						};
						this.trendChartData = {
							categories: ['早餐前', '早餐后', '午餐前', '午餐后', '晚餐前', '晚餐后', '睡前'],
							series: [{
								name: '血糖值',
								data: [5.2, 7.1, 5.8, 7.5, 5.5, 7.2, 6.0]
							}]
						};
						break;
					case 'week':
						// 周数据，7个时间点，显示所有标签，但保持滚动配置
						this.trendOpts = {
							...this.trendOpts,
							enableScroll: true, // 保持滚动启用
							xAxis: {
								...this.trendOpts.xAxis,
								scrollShow: true, // 保持滚动启用
								itemCount: 7
							}
						};
						this.trendChartData = {
							categories: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
							series: [{
								name: '血糖值',
								data: [6.2, 6.5, 7.1, 6.8, 6.3, 5.9, 6.1]
							}]
						};
						break;
					case 'month':
						// 月数据，4个时间点，显示所有标签，但保持滚动配置
						this.trendOpts = {
							...this.trendOpts,
							enableScroll: true, // 保持滚动启用
							xAxis: {
								...this.trendOpts.xAxis,
								scrollShow: true, // 保持滚动启用
								itemCount: 4
							}
						};
						this.trendChartData = {
							categories: ['第1周', '第2周', '第3周', '第4周'],
							series: [{
								name: '血糖值',
								data: [6.3, 6.8, 6.5, 6.2]
							}]
						};
						break;
				}
			},
			switchCompareFilter(type) {
				this.activeCompareFilter = type;
				// 根据不同类型更新对比图表数据
				switch (type) {
					case 'day':
						this.compareChartData = {
							categories: ['12:00', '14:00', '16:00', '17:00', '18:00', '20:00', '22:00'],
							series: [{
								name: '2025-03-02',
								data: [5.5, 8.0, 7.5, 6.8, 7.2, 6.5, 5.8]
							}, {
								name: '2025-03-01',
								data: [6.0, 8.5, 7.8, 7.0, 7.5, 6.8, 6.0]
							}]
						};
						break;
					case 'week':
						this.compareChartData = {
							categories: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
							series: [{
								name: '本周',
								data: [6.2, 6.5, 7.1, 6.8, 6.3, 5.9, 6.1]
							}, {
								name: '上周',
								data: [6.0, 6.3, 6.8, 6.5, 6.2, 5.8, 6.0]
							}]
						};
						break;
					case 'month':
						this.compareChartData = {
							categories: ['第1周', '第2周', '第3周', '第4周'],
							series: [{
								name: '本月',
								data: [6.3, 6.8, 6.5, 6.2]
							}, {
								name: '上月',
								data: [6.1, 6.5, 6.3, 6.0]
							}]
						};
						break;
				}
			},
			addRecord() {
				uni.navigateTo({
					url: '/subPackage_1/pages/index/healthData/add-blood-sugar?targetId=' + this.targetId
				})
			},
			toMoreBloodSugar() {
				uni.navigateTo({
					url: '/subPackage_1/pages/index/healthData/more-blood-sugar',
				});
			},

			listGlucose() {
				listGlucose({
					userId: this.userId
				}).then(res => {
					console.log('API Response:', res)
					if (res.rows && res.rows.length > 0) {
						// 保存原始数据
						const allRows = [...res.rows]
						console.log('All rows:', allRows)

						// 更新记录显示
						if (res.rows.length >= 2) {
							this.records = res.rows.splice(0, 2)
						} else {
							this.records = res.rows
						}
						console.log('Updated records:', this.records)
						console.log(allRows[0].bloodGlucose)

						// 更新图表数据
						if (allRows.length > 0) {
							// 计算血糖值在0-15范围内的比例
							const bloodGlucose = parseFloat(allRows[0].bloodGlucose) || 0
							const proportion = bloodGlucose / 15 // 将血糖值转换为0-1之间的比例

							// 创建新的图表数据对象以确保视图更新
							this.chartData = {
								series: [{
									name: "血糖值",
									color: allRows[0].color || '#fb3f3f',
									data: proportion
								}]
							}

							// 更新opts配置
							this.opts = {
								type: 'arcbar',
								canvasId: 'bloodSugarArc',
								width: 180,
								height: 180,
								background: '#FFFFFF',
								animation: true,
								dataLabel: false,
								title: {
									name: allRows[0].bloodGlucose || '0.0',
									color: allRows[0].color || '#fb3f3f',
									fontSize: 36,
									offsetY: -30
								},
								subtitle: {
									name: "mmol/L",
									color: '#999999',
									fontSize: 14,
									offsetY: -10
								},
								extra: {
									arcbar: {
										type: 'default',
										width: 12,
										backgroundColor: '#F5F5F5',
										startAngle: 0.8,
										endAngle: 0.2,
										gap: 2,
										linearType: 'none',
										roundCap: true
									}
								}
							}
							console.log('Updated chart data:', this.chartData)
						}
					}
				}).catch(err => {
					console.error('Error fetching glucose data:', err)
				})
			},

			queryTrendList() {
				queryTrendList({
					startDate: this.startDate,
					endDate: this.endDate,
					userId: this.userId,
					queryFlag:this.activeFilter
				}).then(res => {
					this.statisticsExce()
					if (res.data && res.data.length > 0) {
						// 从返回数据中提取时间和血糖值，并格式化时间
						const categories = res.data.map(item => {
							// 检查是否为有效的日期格式
							console.log('日期:', item.measuredTime)
							
							const date = new Date(item.measuredTime)
							// 如果日期无效或者是NaN，直接使用原值
							if (isNaN(date.getTime())) {
								return item.measuredTime
							}
							// 如果是有效日期，格式化为MM-DD格式
							return `${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
						})
						const bloodGlucoseData = res.data.map(item => parseFloat(item.bloodGlucose))

						// 根据数据量动态调整横坐标显示策略
						const dataCount = res.data.length
						let itemCount = 7 // 默认显示7个标签
						
						if (dataCount <= 7) {
							// 数据量少，显示所有标签
							itemCount = dataCount
						} else if (dataCount <= 14) {
							// 中等数据量，显示一半标签
							itemCount = Math.ceil(dataCount / 2)
						} else {
							// 大数据量，显示7个标签，启用滚动
							itemCount = 7
						}

						// 更新trendOpts配置
						this.trendOpts = {
							...this.trendOpts,
							enableScroll: dataCount > 7, // 超过7个数据点时启用滚动
							xAxis: {
								...this.trendOpts.xAxis,
								scrollShow: dataCount > 7, // 超过7个数据点时启用横坐标滚动
								itemCount: itemCount, // 动态设置显示的标签数量
								scrollAlign: 'left'
							},
							extra: {
								...this.trendOpts.extra,
								tooltip: {
									showBox: true,
									showArrow: true,
									borderWidth: 0,
									borderRadius: 4,
									fontColor: '#FFFFFF',
									formatter: (item, category, index) => {
										// 获取对应的颜色
										const color = res.data[index]?.color || '#4cd8aa'
										// 设置tooltip背景色
										return {
											text: `血糖值: ${item.data}mmol/L`,
											color: color,
											bgColor: color
										}
									}
								}
							}
						}

						this.trendChartData = {
							categories: categories,
							series: [{
								name: '血糖值',
								data: bloodGlucoseData
							}]
						}
					} else {
						// 如果没有数据，显示默认的空数据状态
						this.trendChartData = {
							categories: ['暂无数据'],
							series: [{
								name: '血糖值',
								data: [0]
							}]
						}
					}
				}).catch(err => {
					console.error('获取趋势数据失败:', err)
				})
			},

			statisticsExce() {
				statisticsExce({
					startDate: this.startDate,
					endDate: this.endDate,
					userId: this.userId
				}).then(res => {
					console.log(res)
					if (res.code === 200 && res.data) {
						// TODO 后台不转了，麻烦（原型设计的就很冲突）
						this.statistics.normalCount = res.data.正常 || 0;
						this.statistics.highCount =(res.data.高血糖?Number(res.data.高血糖):0) + (res.data.偏高?Number(res.data.偏高):0) || 0;
						this.statistics.lowCount = res.data.低血糖 || 0;
					}
				})
			},

			// 添加日期格式化方法
			formatDate(date) {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},

			// 处理开始日期变化
			onStartDateChange(e) {
				this.startDate = e.detail.value;
				this.queryTrendList(this.activeFilter);
			},

			// 处理结束日期变化
			onEndDateChange(e) {
				this.endDate = e.detail.value;
				this.queryTrendList(this.activeFilter);
			},
			
			queryTypeList() {
				queryTypeList({
					targetId: this.targetId
				}).then(res => {
					this.dictsList = res.data
					console.log(this.dictsList)
				})
			}
		}
	};
</script>

<style scoped>
	.blood-sugar-container {
		min-height: 100vh;
		background: #fff;
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15px;
	}

	.view-more {
		color: #7BC691;
		font-size: 13px;
	}

	.latest-blood-sugar {
		padding: 0 15px 20px;
		position: relative;
		overflow: hidden;
	}

	.latest-blood-sugar .section-header {
		position: relative;
		overflow: hidden;
	}

	.latest-blood-sugar .section-header::after {
		content: '';
		position: absolute;
		top: 26rpx;
		left: 10rpx;
		width: 100%;
		height: 50rpx;
		background-image: url('https://www.ruilongan.com/profile/upload/2025/06/27/路径@2x_20250627113158A059.png');
		background-repeat: no-repeat;
		background-position: left top;
		background-size: contain;
		z-index: 1;
	}

	.latest-blood-sugar .section-header text:first-child {
		position: relative;
		z-index: 2;
		font-size: 38rpx;
		font-weight: 500;
		color: #000;
	}

	.latest-blood-sugar .section-header .view-more {
		position: relative;
		z-index: 2;
	}

	.center-value {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		text-align: center;
		z-index: 3;
	}

	.center-value .value {
		display: block;
		font-size: 40px;
		font-weight: 500;
		color: #333;
		line-height: 1.2;
	}

	.center-value .unit {
		display: block;
		font-size: 13px;
		color: #999;
		margin-top: 5px;
	}

	.measure-time {
		text-align: center;
		color: #abaeaf;
		font-size: 13px;
		margin-top: 15px;
		position: relative;
		z-index: 2;
	}

	.blood-sugar-trend {
		/* border-top: 8px solid #f5f5f5; */
		padding: 24rpx;
	}

	.blood-sugar-trend .date-filter {
		display: flex;
		flex-direction: column;
		padding: 0 15px;
		margin-bottom: 10px;
		border-bottom: 1px solid #f5f5f5;
	}

	.blood-sugar-trend .filter-buttons {
		display: flex;
		align-items: center;
		height: 40px;
	}

	.blood-sugar-trend .filter-buttons text {
		margin-right: 8px;
		color: #666;
		font-size: 13px;
		padding: 4px 12px;
		border-radius: 15px;
		background-color: #F5F5F5;
	}

	.blood-sugar-trend .filter-buttons .active {
		color: #fff;
		background-color: #4CD080;
	}

	.date-picker-range {
		display: flex;
		align-items: center;
		justify-content: flex-end;
		padding: 8px 0;
		width: 100%;
	}

	.date-picker-range picker {
		flex: 0 0 auto;
		width: 95px;
	}

	.date-picker-range picker text {
		display: block;
		text-align: center;
		padding: 4px 0;
		font-size: 12px;
		color: #666;
		background: #F5F5F5;
		border-radius: 4px;
	}

	.date-picker-range .separator {
		padding: 0 4px;
		color: #666;
		font-size: 12px;
	}

	.chart-container {
		height: 220px;
		padding: 10px;
		/* 移除容器的滚动设置，让uCharts自己处理滚动 */
		position: relative;
		/* 强制降低图表容器的层级 */
		z-index: 1 !important;
	}
	
	/* 强制降低所有图表组件的层级 */
	.chart-container canvas,
	.chart-container view,
	.charts-box canvas,
	.charts-box view {
		z-index: 1 !important;
		position: relative !important;
	}

	.legend {
		display: flex;
		justify-content: center;
		padding: 10px 0;
		border-top: 1px solid #f5f5f5;
		background-color: #FBFBFD;
		border-radius: 8px;
		margin: 0 15px;
	}

	.legend-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin: 0;
		font-size: 12px;
		color: #666;
		padding: 8px 12px;
		flex: 1;
		position: relative;
	}

	.legend-item:not(:last-child)::after {
		content: '';
		position: absolute;
		right: 0;
		top: 50%;
		transform: translateY(-50%);
		width: 1px;
		height: 60%;
		background-color: #E0E0E0;
	}

	.legend-label {
		display: flex;
		align-items: center;
		margin-bottom: 4px;
	}

	.count {
		font-size: 11px;
		color: #999;
	}

	.count.normal {
		color: #333;
	}

	.count.high {
		color: #ff8080;
	}

	.count.low {
		color: #1b76ff;
	}

	.dot {
		width: 12px;
		height: 8px;
		border-radius: 2px;
		margin-right: 4px;
	}

	.dot.normal {
		background: #10c558;
	}

	.dot.high {
		background: #ff8080;
	}

	.dot.low {
		background: #1b76ff;
	}

	.blood-sugar-compare {
		/* border-top: 8px solid #f5f5f5; */
		padding: 24rpx;
	}

	.blood-sugar-compare .date-filter {
		display: flex;
		align-items: center;
		padding: 0 15px;
		margin-bottom: 10px;
		height: 40px;
		border-bottom: 1px solid #f5f5f5;
	}

	.blood-sugar-compare .date-filter text {
		margin-right: 8px;
		color: #666;
		font-size: 13px;
		padding: 4px 12px;
		border-radius: 15px;
		background-color: #F5F5F5;
	}

	.blood-sugar-compare .date-filter .active {
		color: #fff;
		background-color: #4CD080;
	}

	.blood-sugar-compare .date-filter text:last-child {
		margin-right: 0;
	}

	.date-selector {
		padding: 0 15px;
	}

	.date-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 40px;
		border-bottom: 1px solid #f5f5f5;
		font-size: 13px;
	}

	.date-item text:first-child {
		color: #666;
	}

	.date {
		color: #7BC691;
	}

	.data-records {
		/* border-top: 8px solid #f5f5f5; */
		padding: 24rpx;
		padding-bottom: 24rpx;
		height: 400rpx; /* 增加高度，确保2条记录完全显示 */
		overflow: hidden;
	}

	.record-item {
		padding: 20rpx 30rpx;
		border-bottom: 1px solid #f5f5f5;
		height: 150rpx; /* 每条记录固定高度 */
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		justify-content: center;
	}
	
	/* scroller容器样式 */
	.data-records .scroller {
		height: 320rpx; /* 增加高度，确保2条记录完全显示 */
	}

	.record-main {
		display: flex;
		justify-content: space-between;
		margin-bottom: 10rpx;
		font-size: 14px;
		align-items: center;
	}

	.record-main .value {
		position: static;
		transform: none;
		color: #333;
		font-size: 14px;
		font-weight: normal;
	}

	.status {
		padding: 2px 8px;
		border-radius: 12px;
		font-size: 12px;
	}

	.status.normal {
		background: #F0F9F1;
		color: #7BC691;
	}

	.status.high {
		background: #FFF2F2;
		color: #FF6B6B;
	}

	.record-sub {
		display: flex;
		justify-content: space-between;
		color: #666;
		font-size: 13px;
		margin-bottom: 8rpx;
	}

	.record-time {
		color: #999;
		font-size: 12px;
		margin-top: 5rpx;
	}

	.reference-values {
		border-top: 8px solid #f5f5f5;
		padding-bottom: 180px;
		padding: 24rpx;
	}

	.section-header .unit {
		position: static;
		transform: none;
		color: #999;
		font-size: 12px;
		margin-left: auto;
	}

	.reference-table {
		margin: 0 15px;
		border: 1px solid #f0f0f0;
		border-radius: 8px;
		overflow: hidden;
	}

	.table-row {
		display: flex;
	}

	.table-row.header {
		background: #4cd080;
	}

	.table-row.header .cell {
		color: #fff;
	}

	.cell {
		flex: 1;
		padding: 10px 5px;
		text-align: center;
		font-size: 11px;
		color: #666;
		border-right: 1px solid #f0f0f0;
		border-bottom: 1px solid #f0f0f0;
		display: flex;
		align-items: center;
		justify-content: center;
		min-height: 36px;
	}

	.cell:last-child {
		border-right: none;
	}

	.table-row:last-child {
		background: #ff4c4c;
	}

	.table-row:last-child .cell {
		border-bottom: none;
		color: #fff;
	}

	.reference-table-footer {
		height: 100px;
	}

	.bottom-button {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 15px;
		background: #fff;
		box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.1);
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.bind-device {
		padding-left: 40rpx;
		color: #4CD080;
		font-size: 28rpx;
		cursor: pointer;
	}
	
	/* 绑定设备弹窗样式 */
	.bind-modal-overlay {
		position: fixed !important;
		top: 0 !important;
		left: 0 !important;
		right: 0 !important;
		bottom: 0 !important;
		background-color: rgba(0, 0, 0, 0.6) !important;
		background: rgba(0, 0, 0, 0.6) !important;
		backdrop-filter: blur(4px);
		-webkit-backdrop-filter: blur(4px);
		display: flex !important;
		align-items: center !important;
		justify-content: center !important;
		z-index: 99999 !important;
		/* 确保在移动端正确显示 */
		-webkit-transform: translateZ(0);
		transform: translateZ(0);
		will-change: opacity;
		/* 强制创建新的层叠上下文 */
		isolation: isolate !important;
	}
	
	.bind-modal {
		width: 600rpx;
		max-width: 90vw;
		background-color: #fff !important;
		border-radius: 20rpx;
		overflow: hidden;
		animation: modalShow 0.3s ease-out;
		/* 确保弹窗在移动端正确显示 */
		box-shadow: 0 10rpx 40rpx rgba(0, 0, 0, 0.2);
		-webkit-transform: translateZ(0);
		transform: translateZ(0);
		position: relative !important;
		z-index: 100000 !important;
		/* 确保弹窗内容不被遮挡 */
		isolation: isolate !important;
	}
	
	@keyframes modalShow {
		from {
			opacity: 0;
			transform: scale(0.8);
		}
		to {
			opacity: 1;
			transform: scale(1);
		}
	}
	
	.modal-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 40rpx 40rpx 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}
	
	.modal-title {
		font-size: 36rpx;
		font-weight: 600;
		color: #333;
	}
	
	.modal-close {
		font-size: 48rpx;
		color: #999;
		line-height: 1;
		cursor: pointer;
	}
	
	.modal-content {
		padding: 40rpx;
	}
	
	.input-group {
		margin-bottom: 30rpx;
	}
	
	.input-label {
		display: block;
		font-size: 28rpx;
		color: #333;
		margin-bottom: 20rpx;
		font-weight: 500;
	}
	
	.sn-input {
		width: 100%;
		height: 88rpx;
		border: 2rpx solid #e0e0e0;
		border-radius: 12rpx;
		padding: 0 24rpx;
		font-size: 28rpx;
		color: #333;
		background-color: #fff;
		box-sizing: border-box;
	}
	
	.sn-input:focus {
		border-color: #4CD080;
		outline: none;
	}
	
	.modal-tips {
		background-color: #f8f9fa;
		border-radius: 12rpx;
		padding: 24rpx;
	}
	
	.tips-text {
		display: block;
		font-size: 24rpx;
		color: #666;
		line-height: 1.6;
		margin-bottom: 8rpx;
	}
	
	.tips-text:last-child {
		margin-bottom: 0;
	}
	
	.modal-footer {
		display: flex;
		padding: 20rpx 40rpx 40rpx;
		gap: 20rpx;
	}
	
	.modal-btn {
		flex: 1;
		height: 88rpx;
		border-radius: 12rpx;
		font-size: 32rpx;
		font-weight: 500;
		border: none;
		cursor: pointer;
		transition: all 0.2s;
	}
	
	.cancel-btn {
		background-color: #f5f5f5;
		color: #666;
		border: 2rpx solid #e0e0e0;
	}
	
	.cancel-btn:active {
		background-color: #e8e8e8;
	}
	
	.confirm-btn {
		background-color: #4CD080;
		color: #fff;
	}
	
	.confirm-btn:active {
		background-color: #3bb369;
	}
	
	.confirm-btn:disabled {
		background-color: #ccc;
		color: #999;
		cursor: not-allowed;
	}
	
	/* 移动端优化样式 */
	@media screen and (max-width: 750rpx) {
		.bind-modal {
			width: 90vw;
			margin: 0 5vw;
		}
		
		.bind-modal-overlay {
			background-color: rgba(0, 0, 0, 0.7);
			background: rgba(0, 0, 0, 0.7);
		}
		
		.modal-header {
			padding: 30rpx 30rpx 15rpx;
		}
		
		.modal-content {
			padding: 30rpx;
		}
		
		.modal-footer {
			padding: 15rpx 30rpx 30rpx;
		}
	}
	
	/* 确保在iOS Safari中正确显示 */
	@supports (-webkit-touch-callout: none) {
		.bind-modal-overlay {
			background-color: rgba(0, 0, 0, 0.7) !important;
			background: rgba(0, 0, 0, 0.7) !important;
			z-index: 99999 !important;
		}
	}
	
	/* 强制降低所有图表相关元素的层级 */
	
	/* 弹窗显示时的特殊处理 */
	.bind-modal-overlay:not([style*="display: none"]) ~ * {
		z-index: 1 !important;
	}
	
	/* 强制降低图表组件的层级 */
	qiun-data-charts,
	qiun-data-charts canvas,
	qiun-data-charts view {
		z-index: 1 !important;
		position: relative !important;
	}
	
	/* 当弹窗显示时，强制降低所有图表元素 */
	.modal-open .chart-container,
	.modal-open .charts-box,
	.modal-open qiun-data-charts,
	.modal-open canvas {
		z-index: 1 !important;
		position: relative !important;
	}
	
	/* 当弹窗显示时，直接隐藏图表容器避免遮挡 */
	.modal-open .latest-blood-sugar,
	.modal-open .chart-container,
	.modal-open .charts-box {
		visibility: hidden !important;
		opacity: 0 !important;
		pointer-events: none !important;
	}
	
	/* 确保弹窗始终在最顶层 */
	.bind-modal-overlay {
		z-index: 999999 !important;
		position: fixed !important;
		top: 0 !important;
		left: 0 !important;
		right: 0 !important;
		bottom: 0 !important;
		width: 100% !important;
		height: 100% !important;
	}
	
	.bind-modal {
		z-index: 1000000 !important;
		position: relative !important;
	}

	.add-record {
		background: #10c558;
		color: #fff;
		border-radius: 10px;
		font-size: 15px;
		height: 44px;
		line-height: 44px;
		border: none;
		width: 430rpx;
		margin: 0;
	}

	.blood-sugar-trend .section-header,
	.blood-sugar-compare .section-header,
	.data-records .section-header,
	.reference-values .section-header {
		position: relative;
		overflow: hidden;
	}

	.blood-sugar-trend .section-header::after,
	.blood-sugar-compare .section-header::after,
	.data-records .section-header::after,
	.reference-values .section-header::after {
		content: '';
		position: absolute;
		top: 26rpx;
		left: 10rpx;
		width: 100%;
		height: 50rpx;
		background-image: url('https://www.ruilongan.com/profile/upload/2025/06/27/路径@2x_20250627113158A059.png');
		background-repeat: no-repeat;
		background-position: left top;
		background-size: contain;
		z-index: 1;
	}

	.blood-sugar-trend .section-header text:first-child,
	.blood-sugar-compare .section-header text:first-child,
	.data-records .section-header text:first-child,
	.reference-values .section-header text:first-child {
		position: relative;
		z-index: 2;
		font-size: 38rpx;
		font-weight: 500;
		color: #000;
	}

	.blood-sugar-trend .section-header .view-more,
	.blood-sugar-compare .section-header .view-more,
	.data-records .section-header .view-more,
	.reference-values .section-header .view-more,
	.reference-values .section-header .unit {
		position: relative;
		z-index: 2;
	}

	/* 请根据实际需求修改父元素尺寸，组件自动识别宽高 */
	.charts-box {
		width: 360rpx;
		height: 360rpx;
		margin: 30rpx auto;
	}

	.description {
		padding: 24rpx;
		color: #000;
		font-size: 20rpx;
		line-height: 1.6;
	}

	.description text {
		display: block;
	}

	.description text:first-child {
		margin-bottom: 8rpx;
	}
	
	/* 空状态样式 */
	.empty-state {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 80rpx 40rpx;
		color: #999;
		font-size: 28rpx;
	}
</style>